﻿using System.Collections.Generic;
using System.Data;
using System.Linq;
using Monkey.Warrenty.Data.Interfaces;
using Monkey.Warrenty.EntityModel;

namespace Monkey.Warrenty.Data
{
    public class ErrorDao : IErrorDao
    {
        public List<Error> GetAllErrors()
        {
            List<Error> errors;

            using (var context = new MonkeyWarrantyEntities())
            {
                errors = context.Errors.OrderBy(x => x.Name).ToList();
            }

            return errors;
        }

        public Error AddError(Error error)
        {
            using (var context = new MonkeyWarrantyEntities())
            {
                context.Errors.AddObject(error);
                context.SaveChanges();
            }

            return error;
        }

        public void UpdateError(Error error)
        {
            // throw new System.NotImplementedException();
            if (error == null || error.Id == 0) return;

            using (var context = new MonkeyWarrantyEntities())
            {
                context.Errors.Attach(error);
                context.ObjectStateManager.ChangeObjectState(error, EntityState.Modified);
                context.SaveChanges();
            }
        }

        public void DeleteError(int errorId)
        {
            if (errorId <= 0) return;
            using (var context = new MonkeyWarrantyEntities())
            {
                var error = context.Errors.First(g => g.Id == errorId);

                context.DeleteObject(error);

                context.SaveChanges();
            }
        }

        public int GetMaxId()
        {
            var maxId = 0;

            using (var context = new MonkeyWarrantyEntities())
            {
                var error = context.Errors.OrderByDescending(x => x.Id).FirstOrDefault();
                if (error != null) maxId = error.Id;
            }

            return maxId;
        }

        public int GetCurrentIdentity()
        {
            long? identity;
            using (var context = new MonkeyWarrantyEntities())
            {
                identity = context.GetIdentity("Errors").SingleOrDefault();
            }

            return identity.HasValue ? (int)identity.Value : 0;
        }

        public Error GetById(int id)
        {
            using (var context = new MonkeyWarrantyEntities())
            {
                return context.Errors.FirstOrDefault(x => x.Id == id);
            }
        }
    }
}
